<template>
  <div style="padding: 15px;">
    <el-form ref="form" :model="form" label-width="80px" :rules="rules">
      <el-row>
        <el-col :span="8">
          <div class="grid-content bg-purple">
			      <el-form-item
              label="盘点单号"
              style="margin-right: 15px"
              label-width="120px"
            >
              <el-input
                disabled
                v-model="form.code"
                style="width: 100%"
              ></el-input>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item
              label="所属仓库"
              style="margin-right: 15px"
              label-width="120px"
            >
              <el-input
                disabled
                v-model="form.warehouseName"
                style="width: 100%"
              ></el-input>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
			    <div class="grid-content bg-purple">
            <el-form-item label="盘点类型" style="margin-right:15px"  label-width="120px">
              <el-select v-model="form.type"
                         :disabled="true"
                         @change="selectCountingType(form.type)"
                         placeholder="请输入盘点类型 " style="width:100%" clearable>
                <el-option
                  v-for="item in countingTypeData"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div v-if="showShipment" class="grid-content bg-purple">
            <el-form-item
              label="入驻商"
              style="margin-right: 15px"
              label-width="120px"
            >
              <el-input
                disabled
                v-model="form.shipmentName"
                style="width: 100%"
              ></el-input>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div v-if="showLocation" class="grid-content bg-purple">
            <el-form-item
              label="库位"
              style="margin-right: 15px"
              label-width="120px"
            >
              <el-input
                disabled
                v-model="form.locationName"
                style="width: 100%"
              ></el-input>
            </el-form-item>
            <!-- <el-form-item label="库位" style="margin-right:15px"  label-width="120px">
              <el-select v-model="form.location"
                         :disabled="true"
                         @change="selectLocation(form.location)"
                         placeholder="请选择库位" style="width:100%">
                <el-option
                  v-for="item in locationData"
                  :key="item.code"
                  :label="item.serialNumber"
                  :value="item.code"
                />
              </el-select>
            </el-form-item> -->
          </div>
        </el-col>
        <el-col :span="8">
          <div v-if="showOpQuantity" class="grid-content bg-purple">
            <el-form-item label="动碰次数" style="margin-right:15px"  label-width="120px">
              <el-input v-model="form.opQuantity" placeholder="请输入动碰次数" style="width:100%" :disabled="true"/>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item label="监盘人" style="margin-right:15px"  label-width="120px">
              <el-input v-model="form.supervisor" placeholder="请输入监盘人" style="width:100%" :disabled="true"/>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <div class="grid-content bg-purple">
            <el-form-item label="备注" style="margin-right:15px"  label-width="120px">
              <el-input v-model="form.remarks" placeholder="请输入备注" style="width:100%"/>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
    </el-form>
    <vxe-toolbar id="toolbar_demo3">
      <template v-slot:buttons>
        <el-button @click="insertEvent">新增</el-button>
      </template>
    </vxe-toolbar>
    <vxe-table
      border
      resizable
      show-overflow
      ref="xTable"
      :align="allAlign"
      :data="tableData"
      height="500"
      :loading="loading"
      :edit-rules="validRules"
      show-footer
      keep-source
      @scroll="scrollEvent"
      :edit-config="{trigger: 'click', mode: 'cell'}"
      @edit-actived="editActivedEvent"
      auto-resize
    >
      <vxe-table-column type="seq" width="60" fixed="left" />
      <vxe-table-column field="warehouseSpaceName" title="库区"  :edit-render="{}" width="270">
        <template v-slot:edit="{ row }">
          <el-select v-model="row.warehouseSpaceName" placeholder="请输入库区" style="width:100%" @change="getWarehouseSpaceCode(row)" :disabled="warehouseDisabled">
            <el-option
              v-for="item in warehouseSpaceData"
              :key="item.name"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </template>
      </vxe-table-column>

      <vxe-table-column field="locationName" title="库位" :edit-render="{name: 'ElSelect'}" width="270">
        <template v-slot:edit="{ row }">
          <locationElSelect  :val2="form.warehouseCode" :val1="row.warehouseSpaceCode" :val3="warehouseDisabled" ref="locationElSelect"  @setLocationCode="setLocationCode(row)" />
        </template>
      </vxe-table-column>
      <vxe-table-column field="shipmentName" title="入驻商"  :edit-render="{}" width="270">
        <template v-slot:edit="{ row }">
          <el-select v-model="row.shipmentCode" placeholder="请选择入驻商" style="width:100%" @change="val=>ptypeChangeEvent(row,val)" :disabled="shipmentDisabled">
            <el-option
              v-for="item in shipmentData"
              :key="item.partyCode"
              :label="item.userName"
              :value="item.partyCode"
            />
          </el-select>
        </template>
      </vxe-table-column>

      <!-- <vxe-table-column field="locationName" title="库位" min-width="100"  :edit-render="{name: '$select', optionProps: {'value': 'code', 'label': 'serialNumber'},options: locationData,props: {disabled: Disabled}}"/> -->
      <!-- <vxe-table-column field="shipmentCode" title="入驻商" min-width="100" :edit-render="{name: '$select',optionProps: {'value': 'code', 'label': 'name'}, options: shipmentData,events: {change: ptypeChangeEvent},props: {disabled: shipmentDisabled }}"/> -->
      <vxe-table-column field="goodsName" title="商品名称" :edit-render="{name: 'ElSelect'}" width="270">
        <template v-slot:edit="{ row }">
          <goodsSelect :val2="row.shipmentCode" :val1="Disabled" ref="goodsSelect"  @setGoodsCode="setGoodsCode(row)" />
        </template>
      </vxe-table-column>
      <vxe-table-column field="goodCode" title="商品编码"  width="120"></vxe-table-column>
      <vxe-table-column field="goodsBarCode" title="商品条码"  width="120"></vxe-table-column>
      <vxe-table-column field="goodsUnitName" title="单位"  width="120"></vxe-table-column>

      <vxe-table-column field="inventoryQuantity" title="库存数量" min-width="100" :edit-render="{name: 'input', defaultValue: '0',attrs: {disabled: true}}"/>
      <vxe-table-column field="statusName" title="盘点状态"  width="120"></vxe-table-column>
      <vxe-table-column field="countingQuantity" title="盘点数量" min-width="100" :edit-render="{name: 'input', events: {change: countingQuantityChange}}"/>

      <!-- <vxe-table-column field="goodsStatusName" title="库存状态" min-width="100"  :edit-render="{name: '$select', optionProps: {'value': 'code', 'label': 'name'}, options: inventoryStatuses,props: {disabled: Disabled}}"/> -->
      <vxe-table-column field="goodsStatusName" title="库存状态"  :edit-render="{}" width="270">
        <template v-slot:edit="{ row }">
          <el-select v-model="row.goodsStatusName" placeholder="请选择库存状态" style="width:100%" :disabled="Disabled" @change="selectGoodsUnitCode($event, row)">
            <el-option
              v-for="item in row.inventoryStatuses"
              :key="item.name"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </template>
      </vxe-table-column>

      <!-- <vxe-table-column field="isLock" title="锁定状态" min-width="120"  :edit-render="{name: '$select', options: lockList, props: {disabled: Disabled}}"/> -->

      <vxe-table-column field="isLock" title="锁定状态" min-width="120" :edit-render="{}" :formatter="formatterIsLock">
        <template v-slot:edit="{ row }">
          <el-select v-model="row.isLock" :disabled="Disabled" placeholder="请选择" style="width:100%">
            <el-option
              v-for="item in lockList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </template>
      </vxe-table-column>

      <vxe-table-column field="gmtManufacture" title="生产日期" :edit-render="{autofocus: '.vxe-input--inner'}" min-width="150">
        <template v-slot:edit="{ row }">
          <vxe-input v-model="row.gmtManufacture" placeholder="日期选择" type="date" :disabled='row.batchRule == undefined ||row.batchRule.gmtManufacture !== 1'></vxe-input>
        </template>
      </vxe-table-column>
      <vxe-table-column field="gmtExpire" title="过期日期" :edit-render="{autofocus: '.vxe-input--inner'}" min-width="150">
        <template v-slot:edit="{ row }">
          <vxe-input v-model="row.gmtExpire" placeholder="日期选择" type="date" :disabled='row.batchRule == undefined ||row.batchRule.gmtExpire !== 1'></vxe-input>
        </template>
      </vxe-table-column>
      <vxe-table-column field="gmtStock" title="存货日期" :edit-render="{autofocus: '.vxe-input--inner'}" min-width="150">
        <template v-slot:edit="{ row }">
          <vxe-input v-model="row.gmtStock" placeholder="日期选择" type="date" :disabled='row.batchRule == undefined ||row.batchRule.gmtStock !== 1'></vxe-input>
        </template>
      </vxe-table-column>
      <vxe-table-column field="receiveLot" title="收货批次" min-width="120" :edit-render="{autofocus: '.vxe-input--inner'}">
        <template v-slot:edit="{ row }">
          <vxe-input type="text" v-model="row.receiveLot" :disabled='row.batchRule == undefined ||row.batchRule.receiveLot !== 1'></vxe-input>
        </template>
      </vxe-table-column>
      <vxe-table-column field="supplier" title="供应商" min-width="120" :edit-render="{autofocus: '.vxe-input--inner'}">
        <template v-slot:edit="{ row }">
          <vxe-input type="text" v-model="row.supplier" :disabled='row.batchRule == undefined ||row.batchRule.supplier !== 1'></vxe-input>
        </template>
      </vxe-table-column>
      <vxe-table-column field="serialNumber" title="序列号" min-width="120" :edit-render="{autofocus: '.vxe-input--inner'}">
        <template v-slot:edit="{ row }">
          <vxe-input type="text" v-model="row.serialNumber" :disabled='row.batchRule == undefined ||row.batchRule.serialNumber !== 1'></vxe-input>
        </template>
      </vxe-table-column>
      <vxe-table-column field="extendOne" title="生产批号" min-width="120" :edit-render="{autofocus: '.vxe-input--inner'}">
        <template v-slot:edit="{ row }">
          <vxe-input type="text" v-model="row.extendOne" :disabled='row.batchRule == undefined ||row.batchRule.extendOne !== 1'></vxe-input>
        </template>
      </vxe-table-column>
      <vxe-table-column field="extendTwo" title="商品批次" min-width="120" :edit-render="{autofocus: '.vxe-input--inner'}">
        <template v-slot:edit="{ row }">
          <vxe-input type="text" v-model="row.extendTwo" :disabled='row.batchRule == undefined ||row.batchRule.extendTwo !== 1'></vxe-input>
        </template>
      </vxe-table-column>
      <vxe-table-column field="extendThree" title="扩展3" min-width="120" :edit-render="{autofocus: '.vxe-input--inner'}">
        <template v-slot:edit="{ row }">
          <vxe-input type="text" v-model="row.extendThree" :disabled='row.batchRule == undefined ||row.batchRule.extendThree !== 1'></vxe-input>
        </template>
      </vxe-table-column>
      <vxe-table-column field="extendFour" title="扩展4" min-width="120" :edit-render="{autofocus: '.vxe-input--inner'}">
        <template v-slot:edit="{ row }">
          <vxe-input type="text" v-model="row.extendFour" :disabled='row.batchRule == undefined ||row.batchRule.extendFour !== 1'></vxe-input>
        </template>
      </vxe-table-column>
      <vxe-table-column field="extendFive" title="扩展5" min-width="120" :edit-render="{autofocus: '.vxe-input--inner'}">
        <template v-slot:edit="{ row }">
          <vxe-input v-model="row.extendFive" placeholder="日期选择" type="date" :disabled='row.batchRule == undefined ||row.batchRule.extendFive !== 1'></vxe-input>
        </template>
      </vxe-table-column>
      <vxe-table-column field="extendSix" title="扩展6" min-width="120" :edit-render="{autofocus: '.vxe-input--inner'}">
        <template v-slot:edit="{ row }">
          <vxe-input v-model="row.extendSix" placeholder="日期选择" type="date" :disabled='row.batchRule == undefined ||row.batchRule.extendSix !== 1'></vxe-input>
        </template>
      </vxe-table-column>

      <!-- <vxe-table-column field="gmtManufacture" title="生产日期" min-width="150" :edit-render="{name: '$input', props: {type: 'date',disabled: gmtManufactureDisabled},}"/> -->
      <!-- <vxe-table-column field="gmtExpire" title="过期日期" min-width="150"  :edit-render="{name: '$input', props: {type: 'date',disabled: gmtExpireDisabled},}"/>
      <vxe-table-column field="gmtStock" title="存货日期" min-width="150" :edit-render="{name: '$input', props: {type: 'date',disabled: gmtStockDisabled},}"/>
      <vxe-table-column field="receiveLot" title="收货批次" min-width="100" :edit-render="{name: 'input',attrs: {disabled: receiveLotDisabled}}"/>
      <vxe-table-column field="supplier" title="供应商" width="120"  :edit-render="{name: 'input',attrs: {disabled: supplierDisabled}}"/>
      <vxe-table-column field="serialNumber" title="序列号" width="120"  :edit-render="{name: 'input',attrs: {disabled: serialNumberDisabled}}"/>
      <vxe-table-column field="extendOne" title="生产批号" width="120"  :edit-render="{name: 'input',attrs: {disabled: extendOneDisabled}}"/>
      <vxe-table-column field="extendTwo" title="商品批次" width="120"  :edit-render="{name: 'input',attrs: {disabled: extendTwoDisabled}}"/>
      <vxe-table-column field="extendThree" title="扩展3" width="120"  :edit-render="{name: 'input',attrs: {disabled: extendThreeDisabled}}"/>
      <vxe-table-column field="extendFour" title="扩展4" width="120"  :edit-render="{name: 'input',attrs: {disabled: extendFourDisabled}}"/>
      <vxe-table-column field="extendFive" title="扩展5" min-width="150" :edit-render="{name: '$input', props: {type: 'date',disabled: extendFiveDisabled},}"/>
      <vxe-table-column field="extendSix" title="扩展6" min-width="150" :edit-render="{name: '$input', props: {type: 'date',disabled: extendSixDisabled},}"/> -->
      <vxe-table-column title="操作" fixed="right" min-width="170">
        <template slot-scope="scope">
          <vxe-button v-if="scope.row.code == undefined || scope.row.countingItemCode == undefined" type="text" @click="removeEvent(scope.row)">
            <i class="el-icon-minus" />
          </vxe-button>
        </template>
      </vxe-table-column>
    </vxe-table>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="funcSave" :disabled="isDisable" plain>保 存</el-button>
      <el-button type="primary" @click="funcSubmit" :disabled="isDisable" plain>提 交</el-button>
    </div>
  </div>
</template>
<script>
import Vue from 'vue'
import 'xe-utils'
import VXETable from 'vxe-table'
import 'vxe-table/lib/index.css'
import XEUtils from 'xe-utils'
import VXEUtils from 'vxe-utils'
import request from '@/utils/request'
import VXETablePluginElement from 'vxe-table-plugin-element'
import 'vxe-table-plugin-element/dist/style.css'
import { countingRegister, countingCheckSubmit, registerDetailPaginate } from '@/api/store'
import {getWarehouse} from '@/api/basicInfo'
import goodsSelect from '@/views/components/goodsElSelect.vue'
import locationElSelect from '@/views/components/locationElSelect.vue'

Vue.use(VXETable, VXEUtils, XEUtils, { mounts: ['cookie'] })
VXETable.use(VXETablePluginElement)
  export default {
  name: 'Parent',
    components: {
      goodsSelect,
      locationElSelect
    },
    data() {
      return {
        allAlign:'center',
        shipmentDisabled:false,
        isDisable:false,   //确定键显示按钮
        tableData: [],
        showShipment: false,
        warehouseDisabled:false,
        deleteCodes:[],
        showLocation: false,
        Disabled: false,
        showOpQuantity: false,
        warehouseData:[],//仓库列表
        shipmentData:[],
        locationData:[],
        warehouseSpaceData:[],
        goodsData:[],
        lockList: [
          { value: 0, label: "否" },
          { value: 1, label: "是" },
        ],
        inventoryStatuses: [
          // { value: "0", label: "合格" },
          // { value: "1",label: "不合格" },
        ],
      validRules: {
        extendThree: [
          // { required: true, message: '数量必须填写' },

          { pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/,  message: '数量必须大于0' },
          { max: 20, message: '数量不能超过20位'}
        ],
        countingQuantity: [
          // { required: true, message: '数量必须填写' },

          { pattern: /^\+?((0|([1-9]+\d*))|((0\.\d+)|([1-9]+\d*\.\d+)))$/,  message: '数量不可为负' },
          { max: 20, message: '数量不能超过20位'}
        ],

        extendFour: [
          // { required: true, message: '数量必须填写' },

          { pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/,  message: '数量必须大于0' },
          { max: 20, message: '数量不能超过20位'}
        ],

      },

        //盘点类型列表
        countingTypeData:[
          { code: "0", name: "全盘" },
          { code: "1",name: "入驻商盘点" },
          { code: "2",name: "库位盘点" },
          { code: "3",name: "动碰盘点" }
        ],
        form: {
          code:'',                                //数据标识 ,
          name:'',                                //库位名称 ,
          remarks:'',                             //备注 ,
          status:'',                              //状态 ,
          total:'',                               //总数 ,
          warehouseCode:'',                       //所属仓库
          supervisor: '',
          deleteCodes:[],
          opQuantity: '',
          shipmentName:'',
          shipmentCode: '',
          warehouseName:'',
          location: '',
          type: '',
          countingRegisterList: []
        },
        loading: false,
        rules: {

        },
        listQuery: {
          total: 0,
          pageNum: 1,
          pageSize: 60,
          code: this.$route.query.code
        },
        timer: null,
        offsetHeight: 0,
        addData:[],
        delData: [],
        editData:[],
      }
    },
    created() {
      this.findLocations()
      this.getWarehouse()
      this.getInfo()
    },
    methods: {
      scrollEvent(e) {
        if (e.isY) {
            // 函数防抖
            if (this.timer) {
              clearTimeout(this.timer)
            }
            this.timer = setTimeout(() => {
                if (this.listQuery.total > (this.tableData.length - this.addData.length)) {
                  this.listQuery.pageNum = this.listQuery.pageNum+1
                  this.getInfo('silentLoading')
                }
            }, 300)
        }
      },
      countingQuantityChange(e) {
        if (!e.row.timestamp) {
          e.row.type='edit'
          if (this.editData.length>0) {
            let isEqual = false
            this.editData.forEach((currentValue, index) => {
              if (currentValue.code === e.row.code) {
                this.editData.splice(index,1,e.row)
                isEqual = true
              }
            });
            if (!isEqual) {
              this.editData.push(e.row)
            }
          } else {
            this.editData.push(e.row)
          }
        }
      },
      // 单位选择
      selectGoodsUnitCode(event, row){
        const sd = row.inventoryStatuses.find(i => i.name == row.goodsStatusName)
        row.goodsStatus = sd.code
        row.goodsStatusName = sd.name
      },

    ptypeChangeEvent (row,val) {
      console.log(row,val)
      // 类型切换时更新级联的下拉数据
      row.goodsStatusName = ''
      const sd = this.shipmentData.find(i => i.partyCode == val)
      row.shipmentName = sd?sd.userName:''
      // row.shipmentCode = sd.partyCode
      request({
        url: '/wms/inventoryStatus/chooseData',
        method: 'get',
        params: { shipmentCode: val }

      }).then(response => {
        row.inventoryStatuses = response.data
      })
    },
    //仓库查询
    getWarehouse(){
      getWarehouse().then(response => {
        this.warehouseData = response.data
        // this.getInfo()
      })
    },
    getWarehouseSpaceCode(row){
      const sd = this.warehouseSpaceData.find(i => i.name == row.warehouseSpaceName)
      row.warehouseSpaceCode = sd.code
      row.locationName = ''
      row.location = ''

    },
    setLocationCode(row){
      let obj = this.$refs.locationElSelect.locationData
      row.locationName = obj?obj.value:''
      row.location = obj?obj.code:''
      // const sd = this.locationData.find(i => i.code == obj)
      // console.log(this.$refs.locationElSelect)
      // row.locationName = sd?sd.serialNumber:''
      // row.location = obj
    },

    //商品选择
    setGoodsCode(row){
      // const sd = this.shipmentData.find(i => i.partyCode == this.form.shipmentCode)
      // row.shipmentName = sd.name
      request({
        url: '/wms/inventoryStatus/chooseData',
        method: 'get',
        params: { shipmentCode: this.form.shipmentCode }

      }).then(response => {
        row.inventoryStatuses = response.data
      })

      let obj = this.$refs.goodsSelect.obj1
      row.goodsName = obj.name
      row.goodsCode = obj.code
      row.goodCode = obj.goodCode
      row.unitName = obj.unitName
      row.unitCode = obj.unitCode
      row.goodsBarCode = obj.barCode
      row.goodsUnitName = obj.basicUnitName
      row.goodsUnitConversionList = obj.goodsUnitConversionList
      row.batchRule = obj.batchRule
      row.supplier = ''
      row.serialNumber = ''
      row.extendOne = ''
      row.extendTwo = ''
      row.extendThree = ''
      row.extendFour = ''
      row.extendFive =''
      row.extendSix = ''
      row.gmtManufacture = ''
      row.gmtExpire =''
      row.gmtStock = ''
      row.receiveLot = ''

    },
    // 新增
    async insertEvent () {
      if(this.form.type == '1'){
        const xTable = this.$refs.xTable
        const newRow = {
          isLock: 0,
          shipmentCode : this.form.shipmentCode,
          shipmentName : this.form.shipmentName,
          inventoryQuantity : '0',
        }
        this.tableData.splice(0, 0, newRow)
      }else if(this.form.type == '2'){
        const xTable = this.$refs.xTable
        const newRow = {
          warehouseSpaceName : this.tableData[0].warehouseSpaceName,
          warehouseSpaceCode : this.tableData[0].warehouseSpaceCode,
          locationName : this.tableData[0].locationName,
          location : this.tableData[0].location,
          inventoryQuantity : '0'
        }
        this.tableData.splice(0, 0, newRow)
      }else{
        const timestamp = new Date().getTime()
        const obj = {timestamp,"shipmentName": this.form.shipmentName,"warehouseSpaceName":null,"locationName":null,"goodsName":null,"goodCode":null,"goodsBarCode":null,"goodsUnitName":null,"inventoryQuantity":"0","statusName":null,"countingQuantity":null,"goodsStatusName":null,"isLock":0,"gmtManufacture":null,"gmtExpire":null,"gmtStock":null,"receiveLot":null,"supplier":null,"serialNumber":null,"extendOne":null,"extendTwo":null,"extendThree":null,"extendFour":null,"extendFive":null,"extendSix":null,"type":"add"}
        this.tableData.unshift(obj)
        this.addData.push(obj)
        setTimeout(() => {
          document.querySelector('.vxe-table--body').scrollIntoView()
        }, 500);
        // xTable.insert().then(({ row }) => xTable.setActiveRow(row))
      }
    },
      removeEvent (row) {
        this.$XModal.confirm('您确定要删除该数据?').then(type => {
          if (type === 'confirm') {
            if (row.type) {
                this.addData.forEach((item, index)=>{
                  if (item.timestamp === row.timestamp) {
                    this.addData.splice(index, 1)
                  }
                })
                this.tableData.forEach((item, index)=>{
                  if (item.timestamp === row.timestamp) {
                    this.tableData.splice(index, 1)
                  }
                })
            } else {
                this.tableData.forEach((item, index)=>{
                  if (item.code === row.code) {
                    this.addData.splice(index, 1)
                    item.type = 'delete'
                    this.delData.push(item)
                  }
                })
            }
            this.$refs.xTable.remove(row)
          }
          if(row.code !== undefined && row.countingItemCode == undefined){
            this.deleteCodes.push(row.code)
          }

        })
      },
      editActivedEvent ({ row, rowIndex }) {
        this.shipmentDisabled = row.countingItemCode !== undefined
        this.warehouseDisabled = row.countingItemCode !== undefined
        this.Disabled = row.countingItemCode !== undefined
        if(this.form.type == '1'){
          this.shipmentDisabled = true
        }
        if(this.form.type == '2'){
          this.warehouseDisabled = true
        }

      },
      // 分页handle
      handlePageChange({ currentPage, pageSize }) {
        this.listQuery.pageNum = currentPage
        this.listQuery.pageSize = pageSize
        this.getInfo()
      },
      // 获取页面信息
      getInfo(silentLoading) {
        if(!silentLoading){
          this.loading = true
        }

        registerDetailPaginate(this.listQuery).then(response => {
          this.form = response.data

          this.tableData = [...this.tableData, ...response.data.returnPage.records]
          this.listQuery.total = response.data.returnPage.total

          if(this.form.type === '0') {
            this.showShipment = false;
            this.showLocation = false;
            this.showOpQuantity = false;
          }
          if(this.form.type === '1') {
            this.showShipment = true;
            this.showLocation = false;
            this.showOpQuantity = false;
            this.findShipments();
          }
          if(this.form.type === '2') {
            this.showLocation = true;
            this.showShipment = false;
            this.showOpQuantity = false;
            this.findLocations();
          }
          if(this.form.type == 3) {
            this.showOpQuantity = true;
            this.showLocation = false;
            this.showShipment = false;
          }
          this.findWarehouseSpaces()
          this.findShipments()

          this.loading = false
        })
      },
      formatterGoodsCode({ cellValue, row }) {
        return row.productCode;
      },
      formatterGoodsUnit({ cellValue, row }) {
        return row.unitName;
      },
      formatterLocation({ cellValue, row }) {
        row.location = row.locationName;
        return row.locationName;
      },
      formatterStatus({ cellValue, row }) {
        row.inventoryCode = row.code;
        if (row.status === '0') {
          return '合格'
        } else if (row.status === '1') {
          return '不合格'
        }
      },
      formatterLock({ cellValue, row }) {
        row.lock = row.lockName;
        if (cellValue === 0) {
          return '否'
        } else if (cellValue === 1) {
          return '是'
        }
      },
      formatterIsLock ({ cellValue, row }) {
        if (cellValue === 0 || cellValue === 1) {
          return this.lockList[cellValue].label
        } else {
          row.isLock=0
          return '否'
        }
      },
      // 保存
      funcSave() {
        if (!this.$refs.xTable.tableData.length) {
          this.$message.error('请新增明细数据')
        } else {
          if(this.deleteCodes){
            this.form.deleteCodes = this.deleteCodes
          }
          this.form.countingRegisterList = this.$refs.xTable.tableData
          this.form.status = '0';
          const data = this.form;
          const errMap = this.$refs.xTable.validate().catch(errMap => errMap)
          this.$refs.xTable.validate((valids) => {
            if (valids) {
              this.loading = true
              this.isDisable = true;
              let insertRecords = this.$refs.xTable.getInsertRecords()
              let countingRegisterList = [...this.editData, ...this.addData]
              let newData = JSON.parse(JSON.stringify(data))
              newData.countingRegisterList = countingRegisterList
              countingRegister(newData).then(response => {
                this.$message({ message: response.msg, type: 'success' })
                this.$eventBus.$emit('refreshList')
                this.$store.dispatch("tagsView/delView", this.$route);
                this.$router.push({
                  path: "/kngl/counting"
                });
                this.loading = false
                this.isDisable = false
              }).catch(() => this.isDisable = false,this.loading = false)
            } else {
              this.isDisable = false,this.loading = false
              return false
            }
          })
        }
      },

      funcSubmit() {
        if (!this.$refs.xTable.tableData.length) {
          this.$message.error('请新增明细数据')
        } else {
          if(this.deleteCodes){
            this.form.deleteCodes = this.deleteCodes
          }
          this.loading = true
          this.isDisable = true;
          this.form.countingRegisterList = this.$refs.xTable.tableData
          this.form.status = '1';
          const data = this.form;
          const errMap = this.$refs.xTable.validate().catch(errMap => errMap)
          this.$refs.xTable.validate((valids) => {
            if (valids) {
              let insertRecords = this.$refs.xTable.getInsertRecords()
              let countingRegisterList = [...this.editData, ...this.addData]
              let newData = JSON.parse(JSON.stringify(data))
              newData.countingRegisterList = countingRegisterList
              countingCheckSubmit(newData).then(response => {
                this.$message({ message: response.msg, type: 'success' })
                this.$eventBus.$emit('refreshList')
                this.$store.dispatch("tagsView/delView", this.$route);
                this.$router.push({
                  path: "/kngl/counting"
                });
              }).catch(() => {
                this.loading = false
                this.isDisable = false
              })
            } else {
              this.isDisable = false,this.loading = false
              return false
            }
          })

        }
      },
      // 提交
      // funcSubmit() {
      //   if (!this.$refs.xTable.tableData.length) {
      //     this.$message.error('请新增明细数据')
      //   } else {
      //     this.form.countingRegisterList = this.$refs.xTable.tableData
      //     this.form.status = '1';
      //     const data = this.form;
      //     this.$refs['form'].validate((valid) => {
      //       if (valid) {
      //         this.isDisable = true;
      //         countingCheckSubmit(data).then(response => {
      //           this.$message({ message: response.msg, type: 'success' })
      //           this.$router.push({
      //             path: "/kngl/counting"
      //           });
      //           this.isDisable = false
      //         }).catch(() => this.isDisable = false)
      //       } else {
      //         return false
      //       }
      //     })
      //   }
      // },
      // 取消
      funcCancel() {
        this.$emit('fatherCancelMethod', 'add')
      },
      findShipments() {
        request({
          url: '/wms/warehouseShipment/business/shipments',
          method: 'get',
          params: { warehouseCode: this.form.warehouseCode }

        }).then(response => {
          this.shipmentData = response.data
        })
      },
      findWarehouseSpaces() {
        request({
          url: '/wms/warehouseSpace/chooseData',
          method: 'get',
          params: { warehouseCode: this.form.warehouseCode }

        }).then(response => {
          this.warehouseSpaceData = response.data
        })
      },
      findLocations() {
        request({
          url: '/wms/location/chooseData',
          method: 'get'
        }).then(response => {
          this.locationData = response.data

        })
      }
    }
  }
</script>
<style lang="scss" scoped >
  .dialog-footer {
    margin: 75px auto;
    width: 175px;
    // float: right;
  }
</style>
